package controller

import (
	"github.com/ethereum/go-ethereum/common"
	"github.com/gin-gonic/gin"
	"net/http"
	"shendaNFT/pkg/model"
	"shendaNFT/pkg/web/util"
)

// GetBalance 获取账户余额
func (c *Controller) GetBalance(ctx *gin.Context) {
	address, ok := ctx.GetQuery("address")
	if !ok {
		ctx.JSON(http.StatusBadRequest, util.ErrorResponse("address is null"))
		return
	}
	balance, err := c.client.GetBalance(common.HexToAddress(address))
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(balance.String()))
}

// GetTransaction 获取交易信息
func (c *Controller) GetTransaction(ctx *gin.Context) {
	txHash, ok := ctx.GetQuery("txHash")
	if !ok {
		ctx.JSON(http.StatusBadRequest, util.ErrorResponse("address is null"))
		return
	}
	tx, err := c.client.GetTx(txHash)
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(tx))
}

// GetTransactionInBlock 获取区块中的指定的一条交易信息
func (c *Controller) GetTransactionInBlock(ctx *gin.Context) {
	var param model.GetTxInBlockParam
	if err := ctx.ShouldBindQuery(&param); err != nil {
		ctx.JSON(http.StatusBadRequest, util.ErrorResponse(err.Error()))
		return
	}
	tx, err := c.client.GetTxInBlock(param.BlockNumber, param.TxIndex-1)
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(tx))
}

// GetBlockByNumber 根据区块高度获取区块信息
func (c *Controller) GetBlockByNumber(ctx *gin.Context) {
	var param model.GetBlockParam
	if err := ctx.ShouldBindQuery(&param); err != nil {
		ctx.JSON(http.StatusBadRequest, util.ErrorResponse(err.Error()))
		return
	}
	block, err := c.client.GetBlockByNumber(param.BlockNumber)
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(block))
}

// GetBlockByHash 根据区块哈希获取区块信息
func (c *Controller) GetBlockByHash(ctx *gin.Context) {
	var param model.GetBlockByHashParam
	if err := ctx.ShouldBindQuery(&param); err != nil {
		ctx.JSON(http.StatusBadRequest, util.ErrorResponse(err.Error()))
		return
	}
	block, err := c.client.GetBlockByHash(param.BlockHash)
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(block))
}

// GetBlockNumber 获取最近高度的区块数据
func (c *Controller) GetBlockNumber(ctx *gin.Context) {
	block, err := c.client.GetBlockNumber()
	if err != nil {
		ctx.JSON(http.StatusOK, util.ErrorResponse(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, util.SuccessResponse(block))
}
